package com.retailcloud.thirdpartyservice.config;



import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class AccessTokenCache {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String ACCESS_TOKEN_KEY_PREFIX = "wechat:access_token:";

    public void put(String appId, String accessToken, long expiresIn) {
        String key = ACCESS_TOKEN_KEY_PREFIX + appId;
        redisTemplate.opsForValue().set(key, accessToken, expiresIn, TimeUnit.SECONDS);
    }

    public String get(String appId) {
        String key = ACCESS_TOKEN_KEY_PREFIX + appId;
        return redisTemplate.opsForValue().get(key);
    }

    public boolean isExpired(String appId) {
        String key = ACCESS_TOKEN_KEY_PREFIX + appId;
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire == null || expire <= 0;
    }
}
